const express = require('express');
const router = express.Router();
const pool = require('../config/bd');
const { v4: uuidv4 } = require('uuid');
const { validate: isValidUUID } = require('uuid');

// 创建新评论
router.post('/comments', async (req, res) => {
  try {
    const { value, images } = req.body;

    // 生成评论ID
    const commentId = uuidv4();

    // 构建评论对象（根据实际业务需求调整字段）
    const newComment = {
      id: commentId,
      user_id: req.body.userId, // 假设前端传递userId
      family_id: req.body.familyId || null,
      content: value,
      images: JSON.stringify(images || []), // 存储为JSON格式
    };

    // 执行插入
    const [insertResult] = await pool.execute(
      `INSERT INTO comments 
       (id, user_id, family_id, content, images)
       VALUES (?, ?, ?, ?, ?)`,
      [
        newComment.id,
        newComment.user_id,
        newComment.family_id,
        newComment.content,
        newComment.images
      ]
    );

    // 获取完整评论数据（包含用户信息）
    const [createdComment] = await pool.execute(
      `SELECT 
        c.*, 
        u.nickname as author_name,
        u.avatar as author_avatar
       FROM comments c
       JOIN user u ON c.user_id = u.id
       WHERE c.id = ?`,
      [commentId]
    );

    res.status(201).json({
      code: 201,
      success: true,
      data: createdComment[0],
      message: '评论创建成功'
    });

  } catch (err) {
    console.error('创建评论失败:', err);
    res.status(500).json({
      code: 500,
      message: '创建失败: ' + err.message
    });
  }
});

// 获取评论列表
router.get('/comments', async (req, res) => {
  try {
    const { userId, familyId } = req.query;

    // 新增家庭ID校验（网页6、8的安全过滤建议）
    if (!isValidUUID(familyId)) {
      return res.status(400).json({
        code: 400,
        message: '家庭ID格式异常'
      });
    }

    // 关联用户表获取家庭信息（网页3的关联查询思路）
    let sql = `
      SELECT 
        c.*,
        u.nickname AS author_name,
        u.avatar AS author_avatar,
        u.family_id AS user_family
      FROM comments c
      JOIN user u ON c.user_id = u.id
      WHERE u.family_id = ?  -- 强制家庭过滤（网页6的WHERE子句应用）
    `;
    const params = [familyId];  // 固定家庭ID参数

    // 动态添加用户过滤（保留原功能）
    if (userId) {
      sql += ' AND c.user_id = ?';
      params.push(userId);
    }

    // 排序规则保持不变
    sql += ' ORDER BY c.created_at DESC';

    // 执行查询（网页8的参数化查询建议）
    const [rows] = await pool.execute(sql, params);

    res.json({
      code: 200,
      success: true,
      message: '获取家庭评论成功！',
      data: rows
    });

  } catch (err) {
    console.error('获取评论失败:', err);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误：' + err.message
    });
  }
});

module.exports = router;